import axios from 'axios'
import type { ApiResponse } from '@/types/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: '/api',
  timeout: 30000, // 增加超时时间到30秒
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('accessToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 统一处理响应和错误
apiClient.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API请求错误:', error)
    
    // 处理网络错误
    if (error.code === 'ECONNABORTED') {
      return Promise.reject(new Error('请求超时，请检查网络连接'))
    }
    
    if (error.code === 'ERR_NETWORK') {
      return Promise.reject(new Error('网络连接失败，请检查后端服务是否启动'))
    }
    
    // 处理401未授权错误
    if (error.response?.status === 401) {
      localStorage.removeItem('accessToken')
      localStorage.removeItem('user')
      // 重定向到登录页
      window.location.href = '/login'
    }
    
    // 处理400错误
    if (error.response?.status === 400) {
      const errorMessage = error.response?.data?.message || '请求参数错误'
      return Promise.reject(new Error(errorMessage))
    }
    
    // 处理500错误
    if (error.response?.status >= 500) {
      return Promise.reject(new Error('服务器内部错误，请稍后重试'))
    }
    
    // 返回统一的错误格式
    const errorMessage = error.response?.data?.message || error.message || '请求失败'
    return Promise.reject(new Error(errorMessage))
  }
)

export default apiClient

// 通用API请求方法
export const request = {
  get: <T = any>(url: string, params?: any): Promise<ApiResponse<T>> => {
    return apiClient.get(url, { params })
  },
  
  post: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return apiClient.post(url, data)
  },
  
  put: <T = any>(url: string, data?: any): Promise<ApiResponse<T>> => {
    return apiClient.put(url, data)
  },
  
  delete: <T = any>(url: string): Promise<ApiResponse<T>> => {
    return apiClient.delete(url)
  }
}